package com.tom.zx.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tom.zx.entity.Menu;
import com.tom.zx.service.IMenuService;
import com.tom.zx.vo.DistributionVo;
import com.tom.zx.vo.MenuVo;
import com.tom.zx.vo.ReturnDistributionVo;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Arrays;
import java.util.List;

/**
 * 前端控制器
 *
 * @author 王妍
 * @since 2022-02-20
 */
@RestController
@AllArgsConstructor
@RequestMapping("/zx/menu")
public class MenuController {
  private final IMenuService menuService;

  /**
   * 加载用户菜单
   *
   * @param principal 用户身份
   * @return 返回用户菜单
   */
  @GetMapping("/user")
  public MenuVo loadMenuList(Principal principal) {
    return menuService.loadMenuByUserName(principal.getName());
  }

  @GetMapping("/page")
  public Page<Menu> loadPageUser(Page<Menu> page, Menu menu) {
    return menuService.page(
        page, new LambdaQueryWrapper<Menu>().like(Menu::getName, menu.getName()));
  }

  @GetMapping
  public List<Menu> loadLevel1Menu() {
    return menuService.list(new LambdaQueryWrapper<Menu>().eq(Menu::getParentId, -1));
  }

  /** 为角色分配Id */
  @PostMapping("/role/{roleId}")
  public void configureMenuForRole(
      @PathVariable("roleId") Long roleId, @RequestBody DistributionVo menuIds) {
    menuService.configureMenuForRole(roleId, Arrays.asList(menuIds.getIds()));
  }

  /**
   * 获取角色已经有的菜单和没有的菜单
   *
   * @param roleId 角色Id
   * @return 返回角色的菜单分配
   */
  @GetMapping("role/{roleId}")
  public ReturnDistributionVo<Menu> getMenuDistribution(@PathVariable("roleId") Long roleId) {
    return menuService.getMenuDistribution(roleId);
  }

  @PostMapping
  public void save(@RequestBody Menu menu) {
    menuService.saveOrUpdate(menu);
  }

  @DeleteMapping
  public void delete(@RequestBody Long[] menuIds) {
    menuService.removeBatchByIds(Arrays.asList(menuIds));
  }
}
